package yl.hs.bmipfull.service.system.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.material.IPurchaseContractDao;
import yl.hs.bmipfull.daos.material.IPurchaseReceiptDao;
import yl.hs.bmipfull.daos.material.ISupplierDao;
import yl.hs.bmipfull.daos.system.IWechatUserDao;
import yl.hs.bmipfull.daos.vehiclemanage.ITruckInfoDao;
import yl.hs.bmipfull.pojo.salemanage.LinkerInfoEntity;
import yl.hs.bmipfull.pojo.system.WechatUserEntity;
import yl.hs.bmipfull.pojo.vehiclemanage.TruckInfoEntity;
import yl.hs.bmipfull.security.MD5;
import yl.hs.bmipfull.service.finance.IContractAccountService;
import yl.hs.bmipfull.service.material.ISupplierService;
import yl.hs.bmipfull.service.production.ITransTaskService;
import yl.hs.bmipfull.service.system.IWechatUserService;
import yl.hs.bmipfull.utils.*;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.ShipControlState;

import java.math.BigDecimal;
import java.util.*;

/**
 * 作用:   <br/>
 * 创建时间: 2022-06-14 14:59 <br/>
 *
 * @author 吴高丰
 */
@Service
public class WechatUserServiceImpl extends SystemBaseService implements IWechatUserService {
    @Autowired
    IWechatUserDao dao;
    @Autowired
    ITruckInfoDao truckInfoDao;
    @Autowired
    ITransTaskService transTaskService;
    @Autowired
    ISupplierDao supplierDao;
    @Autowired
    IPurchaseContractDao contractDao;
    @Autowired
    IPurchaseReceiptDao receiptDao;
    @Override
    public WechatUserEntity findByOpenId(String openId) {
        return dao.findByOpenId(openId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveWechatUser(Map<String, Object> model, Long id, String truckplate, String companyid) throws Exception {
        String carnumRegex = "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[警京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{0,1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$";
        if(!truckplate.matches(carnumRegex)){
            return -20;
        }
        Integer result = 0;
        WechatUserEntity entity = null;
        var SaleContractSN=model.get("saleContractSN").toString();
        if(SaleContractSN!=null&& !SaleContractSN.equals("")){
            var contractResult=transTaskService.checkContractControl(SaleContractSN, BigDecimal.ZERO);
            if(contractResult== ShipControlState.AMOUNTOUT){
                return -10;
            }
        }
        var wxentity = dao.findByTruckPlate(truckplate,0);
        if(wxentity==null){
            entity = new WechatUserEntity();
            var chenge = Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            entity.setAddTime(new Date());
            entity.setTruckplate(truckplate);
            entity.setState(0);
            result = dao.insertNew(entity);
        }else{
            entity = wxentity;
            var change = Tl.getChangeLog(entity, model);
            result = dao.update(entity);
        }
        try{
        var supplierSn = model.get("supplierSN");
        if(supplierSn != null){
            if(supplierSn.toString()!=null&& !supplierSn.toString().equals("")){
                var contract = contractDao.querySupplierSn(supplierSn.toString());
                if(contract.size()>0){
                    if(contract.get(0).getInitialAmount()!=null && contract.get(0).getInitialAmount().compareTo(BigDecimal.valueOf(0))>0){
                        var amount= receiptDao.gettatileByContractSn(contract.get(0).getSn());
                        if(contract.get(0).getInitialAmount().compareTo(amount)<50000){
                            return result+1;
                        }
                    }
                }
            }
        }
        }catch (Exception ee){
            Log.error(ee);
        }
        return result;
    }

    @Override
    public Integer saveProjectWechatUser(Map<String, Object> model, Long id) throws Exception {
        Integer result = 0;
        WechatUserEntity entity = null;
        var companyid = model.get("companyid");
        if (id == null) {
            //执行保存
            LinkerInfoEntity linker = linkerDao.findUserByAccount(model.get("mobilePhone").toString());
            entity = new WechatUserEntity();
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            result = dao.insertNew(entity);
            if (result > 0) {
                writeLog(ActionType.CREATE, entity.getOpenId().toString(), "插入微信注册用户信息", Tl.toJson(entity), WechatUserEntity.class);
                var results = WebUtil.requestGet(CK.Active_Server + "/WxUser/find/" + entity.getOpenId());
                JSONObject jo = JSONObject.parseObject(results);
                if (jo.get("code").toString().equals("200") && jo.get("data") != null) {
                    var data = (Map<String, Object>) jo.get("data");
                    if (!companyid.equals(data.get("activationid").toString())) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", data.get("id"));
                        map.put("openid", entity.getOpenId());
                        map.put("activationid", companyid);
                        WebUtil.ActiveRequest(CK.Active_Server + "/WxUser", map);
                    }
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("openid", entity.getOpenId());
                    map.put("activationid", companyid);
                    WebUtil.ActiveRequest(CK.Active_Server + "/WxUser", map);
                }
            }
        } else {
            //执行修改
            entity = findById(id);
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            result = dao.update(entity);
            if (result > 0) {
                writeLog(ActionType.UPDATE, entity.getOpenId(), "更新微信注册用户信息", Tl.toJson(entity), WechatUserEntity.class);
            }
        }

        return result;
    }

    @Override
    public WechatUserEntity findById(Long id) {
        return dao.findById(id);
    }

    @Override
    public WechatUserEntity findByTruckPlate(String truckPlate, int state) {
        return dao.findByTruckPlate(truckPlate,state);
    }
}
